package com.gingersoft.connect.utils

import android.content.Context
import com.gingersoft.connect.bean.MessageBuilder
import java.net.InetSocketAddress
import java.net.URI

class GingerSoftConnect {

    private var webSocketClient: MyWebSocketClient? = null

    fun connect(
        ip: String,
        port: Int,
        connectOutTime: Int = 10000,
        listener: SocketStateListener?
    ): MessageBuilder {
        val uri = URI("ws://$ip:$port")
        webSocketClient = MyWebSocketClient(uri, connectOutTime, listener)
        webSocketClient?.connect()
        // 連接成功後獲得發送類
        return MessageBuilder(this, webSocketClient!!)
    }

    fun disconnect() {
        webSocketClient?.close()
    }

    interface SocketStateListener {
        fun onOpen() {}

        fun onClose(code: Int, reason: String?, remote: Boolean) {}

        fun onError(ex: Exception?) {}
    }


    /**
     * 接收數據的服務
     */
    private var mWebSocketServer: MyWebSocketServer? = null
    private var nsdUtils: NSDUtils? = null

    fun registerDiscoveryService(context: Context) {
        // 註冊NSD，讓後面開啟的KDS能主動找到POS設備，然後從POS設備拿食品信息
        nsdUtils = NSDUtils()
        nsdUtils?.registerKDS(context)
    }

    fun startMsgReceiveService() {
        // 開啟服務，接收KDS發來的消息
        mWebSocketServer = MyWebSocketServer(InetSocketAddress(12581))
        mWebSocketServer?.isReuseAddr = true // 設置地址可複用，避免APP被用戶強制殺掉後，再次打開報錯Address already in use
        mWebSocketServer?.start()
    }

    /**
     * 插入自己的數據處理類
     * 目前系統有的都在Action中，以後新增功能，不需要改這個庫，在KDS和POS端調整即可
     */
    fun inputTransmitter(type: String, process: MsgProcess) {
        MsgParser.parserMap[type] = process
    }

    fun unregisterDiscoveryService() {
        mWebSocketServer?.stop()
    }

}